package oauth2.samples.clientserver.ctrl;

import oauth2.samples.clientserver.model.TokenTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

/**
 * @author chai
 * @since 2020/12/2
 */
@Controller
public class IndexController {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    TokenTask tokenTask;

    @GetMapping("/index.html")
    public String index(String code, Model model) {
        model.addAttribute("msg", tokenTask.getData(code));
        return "index";
    }

    @GetMapping("/refresh_token")
    public String refreshToken(Model model) {
        tokenTask.refreshToken();
        model.addAttribute("msg", "New access_token:" + tokenTask.getAccess_token());
        return "index";
    }

    @GetMapping("/name")
    public String name(Model model) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer" + tokenTask.getAccess_token());
        HttpEntity<HttpHeaders> httpEntity = new HttpEntity<>(headers);
        // 获取用户的详细信息
        ResponseEntity<String> entity = restTemplate.exchange("http://127.0.0.1:8081/name", HttpMethod.GET, httpEntity, String.class);
        model.addAttribute("msg", entity.getBody());
        return "index";
    }

}
